from django.shortcuts import render
from django.http import JsonResponse
from django.db.models import Count
from datetime import datetime


def chart_list(request):
    """ 数据统计页面 """
    return render(request, 'chart_list.html')


def chart_bar(request):
    """ 构造柱状图的数据 """
    current_admin_org_id = request.session.get('admin_info', {}).get('org_id')
    task_data = models.Task.objects.filter(org_id=current_admin_org_id)

    distribution_data = {}
    for task in task_data:
        department = task.user.depart  # 获取任务负责人所在部门，假设Admin模型有depart字段
        level = task.level

        if department not in distribution_data:
            distribution_data[department] = {1: 0, 2: 0, 3: 0}

        distribution_data[department][level] += 1

    legend = ["紧急", "重要", "临时"]
    series_list = []
    x_axis = []
    x_axis = [str(department) for department in distribution_data.keys()]
    # 遍历每个任务级别，准备series_list数据
    for level_index, level_name in enumerate(legend):
        data_series = []
        for department, levels_count in distribution_data.items():
            if level_index + 1 in levels_count:
                data_series.append(levels_count[level_index + 1])
            else:
                data_series.append(0)

        series_list.append({
            "name": level_name,
            "type": 'bar',  # 因为是绘制柱状图，所以类型设为'bar'
            "data": data_series
        })

    result = {
        "status": True,
        "data": {
            'legend': legend,
            'series_list': series_list,
            'x_axis': x_axis
        }
    }

    return JsonResponse(result)


    # 数据可以去数据库中获取
    # legend = ["安全部", "IT部","运营部"]
    # series_list = [
    #     {
    #         "name": '紧急',
    #         "type": 'bar',
    #         "data": [15, 20, 36, 10, 10, 10]
    #     },
    #     {
    #         "name": '员工2号',
    #         "type": 'bar',
    #         "data": [45, 10, 66, 40, 20, 50]
    #     }
    # ]
    # x_axis = ['1月', '2月', '4月', '5月', '6月', '7月']
    #
    # result = {
    #     "status": True,
    #     "data": {
    #         'legend': legend,
    #         'series_list': series_list,
    #         'x_axis': x_axis,
    #     }
    # }
    # return JsonResponse(result)


def chart_pie(request):
    """ 构造饼图的数据 """
    current_admin_org_id = request.session.get('admin_info', {}).get('org_id')
    department_employee_count = models.Department.objects.filter(org_id=current_admin_org_id).annotate(
        employee_count=Count('userinfo')).values('title', 'employee_count')
    db_data_list = []
    for item in department_employee_count:
        db_data_list.append({"value": item['employee_count'], "name": item['title']})
    result = {
        "status": True,
        "data": db_data_list
    }
    return JsonResponse(result)

    # db_data_list = [
    #     {"value": 2048, "name": 'IT部门'},
    #     {"value": 1735, "name": '运营部门'},
    #     {"value": 580, "name": '新媒体部门'},
    # ]
    #
    # result = {
    #     "status": True,
    #     "data": db_data_list
    # }
    # return JsonResponse(result)


def chart_line(request):
    # 获取所有已完成订单
    current_admin_org_id = request.session.get('admin_info', {}).get('org_id')
    completed_orders = models.Order.objects.filter(status=2,org_id=current_admin_org_id)

    department_orders = {}
    for order in completed_orders:
        # 获取订单时间的月份
        order_date = datetime.strptime(order.oid[:8], '%Y%m%d')
        month = order_date.month
        admin_id = order.admin_id
        # 获取管理员对应的部门
        try:
            department = models.Admin.objects.get(id=admin_id).depart
        except models.Admin.DoesNotExist:
            continue

        if department not in department_orders:
            department_orders[department] = {}
        if month not in department_orders[department]:
            department_orders[department][month] = 0
        department_orders[department][month] += order.price

    legend = []
    series_list = []
    x_axis = []
    for month in range(1, 13):
        x_axis.append(str(month) + '月')
    for department, months_data in department_orders.items():
        legend.append(department.title)
        data_series = []
        for month in range(1, 13):
            if month in months_data:
                data_series.append(months_data[month])
            else:
                data_series.append(0)
            # if month not in x_axis:
            #     x_axis.append(str(month) + '月')
        series_list.append({
            "name": department.title,
            "type": 'line',
            "stack": 'Total',
            "data": data_series
        })

    result = {
        "status": True,
        "data": {
            'legend': legend,
            'series_list': series_list,
            'x_axis': x_axis,
        }
    }
    return JsonResponse(result)



    # legend = ["研发部", "IT部"]
    # series_list = [
    #     {
    #         "name": '研发部',
    #         "type": 'line',
    #         "stack": 'Total',
    #         "data": [15, 20, 36, 10, 10, 10]
    #     },
    #     {
    #         "name": 'IT部',
    #         "type": 'line',
    #         "stack": 'Total',
    #         "data": [45, 10, 66, 40, 20, 50]
    #     }
    # ]
    # x_axis = ['1月', '2月', '4月', '5月', '6月', '7月']
    #
    # result = {
    #     "status": True,
    #     "data": {
    #         'legend': legend,
    #         'series_list': series_list,
    #         'x_axis': x_axis,
    #     }
    # }
    # return JsonResponse(result)


def highcharts(request):
    """ highcharts示例 """

    return render(request, 'highcharts.html')


from django.forms import ModelForm, Form
from django import forms
from app01 import models


# class TTModelForm(Form):
#     name = forms.CharField(label="用户名")
#     ff = forms.FileField(label="文件")
#
#
# def tt(request):
#     if request.method == "GET":
#         form = TTModelForm()
#         return render(request, 'change.html', {"form": form})
#     form = TTModelForm(data=request.POST, files=request.FILES)
#     if form.is_valid():
#         print(form.cleaned_data)
#     return render(request, 'change.html', {"form": form})

class TTModelForm(ModelForm):
    class Meta:
        model = models.XX
        fields = "__all__"


def tt(request):
    instance = models.XX.objects.all().first()
    if request.method == "GET":
        form = TTModelForm(instance=instance)
        return render(request, 'tt.html', {"form": form})
    form = TTModelForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        form.save()
    return render(request, 'tt.html', {"form": form})

